#!/bin/sh
#
# /etc/rc.d/rc.doos
#
# Start/stop/restart the doos server.
#
# To make doos start automatically at boot, make this
# file executable:  chmod 755 /etc/rc.d/rc.doos
#

PYTHONPATH=/opt/openoffice.org3/program
DOOSPATH=/usr/local/doos
PATH=${DOOSPATH}:${PYTHONPATH}:/usr/local/bin:/usr/bin:/bin

start() {
	echo -n "Starting doos"
 	/bin/su nobody -c "${PYTHONPATH}/python ${DOOSPATH}/doos.py > /dev/null 2>&1 &"

	ps=`ps aux | grep doos | grep -v grep | grep -v rc\.doos`
	sleep 2

	for ((a=0; a < 5; a++)); do
		echo -n "."
		if [[ ${#ps} > 0 ]]; then
			echo " OK"
			return
		fi

		sleep 2
		ps=`ps aux | grep doos | grep -v grep | grep -v rc\.doos`
	done

	echo " FAIL???"
}

stop() {
	echo -n "Stopping doos"
  ${DOOSPATH}/clients/simpleClient.py terminate > /dev/null 2>&1
	ps=`ps aux | grep doos | grep -v grep | grep -v rc\.doos`
	sleep 2

	for ((a=0; a < 15; a++)); do
		echo -n "."
		if [[ ${#ps} = 0 ]]; then
			echo " OK"
			return
		fi
		
		sleep 2
		ps=`ps aux | grep doos | grep -v grep | grep -v rc\.doos`
	done

	echo " FAIL???"
}

restart() {
  stop
	sleep 5
  start
}

case "$1" in
  'start')
    start
  ;;
  'stop')
    stop
  ;;
  'restart')
    restart
  ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
  ;;
esac
